<template>
  <div class="top_tool_bar_max">
    <div v-for="(item, index) in btnList" :key="index" placement="bottom">
      <div @click="handleClick(item.name)" class="item-space">
        <el-button type="primary"> {{ item.title }}</el-button>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {DataUri} from '@antv/x6';
import {defineComponent, onMounted, ref} from "vue";
import {FlowGraph} from '../common/FlowGraph';
// import {addChartTemplate, editChartTemplate, deleteChartTemplate, getChartTemplateList} from '@/api/task/tree'
import {ResultEnum} from "@/enums/httpEnum";
import {useRoute} from "vue-router";
//添加
// import {
//   DeleteOutlined,
//   UndoOutlined,
//   RedoOutlined,
//   CopyOutlined,
//   ScissorOutlined,
//   BlockOutlined
// } from '@ant-design/icons-vue'
interface IFBtnIcon {
  title: string;
  name: string;
  icon?: string;
  text?: string;
}

const route = useRoute();
const btnList: IFBtnIcon[] = [
  {title: '清空画布', name: 'clear', icon: 'delete-outlined'},
  {title: '撤销 ctrl+z', name: 'undo', icon: 'undo-outlined'},
  // { title: '重做 ctrl+d', name: 'redo', icon: 'redo-outlined' },
  // { title: '复制 ctrl+c', name: 'copy', icon: 'copy-outlined' },
  // { title: '剪切 ctrl+x', name: 'cut', icon: 'scissor-outlined' },
  // { title: '粘贴 ctrl+v', name: 'paste', icon: 'block-outlined' },
  {title: '保存PNG', name: 'savePNG', text: 'png'},
  // { title: '保存SVG', name: 'saveSVG', text: 'svg' },
  // { title: '导出', name: 'toJSON', text: 'json' },
  {title: '打印 ctrl+p', name: 'print', text: '打印'},
  {title: '保存', name: 'save', text: '保存'},
  // { title: '删除', name: 'delete', text: '删除' },
  // { title: '查询', name: 'search', text: '查询' },
];
// const message = useMessage();
const graph = FlowGraph.graph;
const {history} = graph;
const canUndo = ref(history.canUndo());
const canRedo = ref(history.canRedo());
const copy = () => {
  const cells = graph.getSelectedCells();
  if (cells.length) {
    graph.copy(cells);
  }
  return false;
};
const cut = () => {
  const cells = graph.getSelectedCells();
  if (cells.length) {
    graph.cut(cells);
  }
  return false;
};
const paste = () => {
  if (!graph.isClipboardEmpty()) {
    const cells = graph.paste({offset: 32});
    graph.cleanSelection();
    graph.select(cells);
  }
  return false;
};
const handleClick = (name: string) => {
  switch (name) {
    case 'undo':
      graph.history.undo();
      break;
    case 'redo':
      graph.history.redo();
      break;
    case 'clear':
      graph.clearCells();
      break;
    case 'savePNG':
      graph.toPNG(
          (dataUri: string) => {
            // 下载
            DataUri.downloadDataUri(dataUri, 'chartx.png');
          },
          {
            backgroundColor: 'white',
            padding: {
              top: 20,
              right: 30,
              bottom: 40,
              left: 50,
            },
            quality: 1,
          }
      );
      break;
    case 'saveSVG':
      graph.toSVG((dataUri: string) => {
        // 下载
        DataUri.downloadDataUri(DataUri.svgToDataUrl(dataUri), 'chart.svg');
      });
      break;
    case 'print':
      graph.printPreview();
      break;
    case 'copy':
      copy();
      break;
    case 'cut':
      cut();
      break;
    case 'paste':
      paste();
      break;
      // case 'toJSON':
      //   console.log(graph.toJSON());
      //   graph.fromJSON({cells:[graph.toJSON().cells[0],graph.toJSON().cells[1]]})
      //   break;
    case 'save':
      // console.log(graph.getNodes())
      let verifyFlag = true // flag
      // 驗證沒有輸入邊的節點參數不可為空
      let nodes = graph.getNodes()
      let nArr = [] as any
      nodes.map(item => {
        // getOutgoingEdges()
        if (graph.getIncomingEdges(item) == null) {  //没有输入边的节点存起来
          nArr.push(item)
        }
      })
      nArr.map(item => {
        if (item.store.data.paramList == '') {
          // message.warning(`${item.store.data.name}节点的参数值不可为空`)
          verifyFlag = false
        }
      })


      // 遍历画布上的元素做个保存前的校验提示 start
      graph.toJSON()?.cells.map(item => {
        if (item.shape !== 'edge') {  // 元素不是连线时

          // 差值属性验证
          // if(item.shape=='Chazhi'){
          //
          // }
          // 对比属性验证
          if (item.shape == 'Duibi') {
            if (item?.propertyList?.value == '') {
              // message.error(`对比节点属性未填写`)
              verifyFlag = false
            }
          }
          // 阈值属性验证
          if (item.shape == 'Yuzhi') {
            if (item.propertyList.upperLimit == '' || item.lowerLimit == '') {
              console.log('123456')
              // message.error(`阈值节点属性未填写`)
              verifyFlag = false
            }
          }

          // //参数验证
          // item?.paramList?.split(';')?.some((item2,index)=>{
          //   if(item2==''){
          //     message.warning(`${item.name}节点的第${index+1}个参数值不可为空`)
          //     verifyFlag=false
          //     return true;
          //   }
          // })
        }
      })
      // 校验参数end

      // 发送请求存储画布信息
      let data = graph.toJSON()
      let id = route.params.id
      // if(verifyFlag){
      //   treeDetail(id,data).then(res=>{
      //     if(res.code==200){
      //       message.success(`决策树保存${res.msg}`)
      //     }
      //   }).catch(err=>{
      //     message.error(err.msg)
      //     console.log(err)
      //   })
      // }

      // treeDetail(id,data).then(res=>{
      //   if(res.code==200){
      //     message.success(`决策树保存${res.msg}`)
      //   }
      // }).catch(err=>{
      //   message.error(err.msg)
      //   console.log(err)
      // })
      break;
    case 'delete':
      // getChartTemplateList('aa6ea58507ada7942805352dd729b655').then(res => {
      //   if(res.code === ResultEnum.SUCCESS) {
      //     res.data.forEach(res => {
      //       deleteChartTemplate(res.id).then(res => {
      //         if(res.code === ResultEnum.SUCCESS) {
      //           message.success('任务图模板删除成功');
      //           let chartTemplate: any = ref([])
      //           getChartTemplateList('aa6ea58507ada7942805352dd729b655').then(res => {
      //             if(res.code === ResultEnum.SUCCESS) {
      //               res.data.forEach(item => {
      //                 if(item.type === 2) {
      //                   chartTemplate = JSON.parse(item.detail)
      //                 }
      //               })
      //               message.success('导调查询成功');
      //               graph.fromJSON(chartTemplate);
      //             }
      //           })
      //         }
      //       })
      //     })
      //   }
      // })

      break;
      // case 'search':
      //   let missionId = {
      //     id: '9d10d9d2d99cc65045da615a5294b194',
      //   }
      //   break;
    default:
      break;
  }
};
history.on('change', () => {
  canUndo.value = history.canUndo();
  canRedo.value = history.canRedo();
});
// 快捷键绑定
graph.bindKey('ctrl+z', () => {
  if (history.canUndo()) {
    history.undo();
  }
  return false;
});
graph.bindKey('ctrl+shift+z', () => {
  if (history.canRedo()) {
    history.redo();
  }
  return false;
});
graph.bindKey('ctrl+d', () => {
  graph.clearCells();
  return false;
});
graph.bindKey('ctrl+s', () => {
  graph.toPNG((datauri: string) => {
    DataUri.downloadDataUri(datauri, 'chart.png');
  });
  return false;
});
graph.bindKey('ctrl+p', () => {
  graph.printPreview();
  return false;
});
graph.bindKey('ctrl+c', copy);
graph.bindKey('ctrl+v', paste);
graph.bindKey('ctrl+x', cut);

// export default defineComponent({
//   name: 'TopToolBar',
//   components: {
//     // DeleteOutlined,
//     // UndoOutlined,
//     // RedoOutlined,
//     // CopyOutlined,
//     // ScissorOutlined,
//     // BlockOutlined
//   },
//   setup() {
//
//     return {
//       canUndo,
//       canRedo,
//       copy,
//       cut,
//       paste,
//       handleClick,
//       btnList,
//     };
//   },
// });
</script>

<style lang="scss" scoped>
.top_tool_bar_max {
  width: 100%;
  height: 40px;
  position: absolute;
  z-index: 100;
  top: 0;
  left: 0;
  display: flex;
  align-items: center;
  box-sizing: border-box;
  border-bottom: 1px solid #d9d9d9;
}

.item-space {
  margin-left: 16px;
}
</style>
